import { useEffect, useState } from 'react';

// 声明全局变量，以便TypeScript能识别微信API
declare global {
  interface Window {
    WeixinJSBridge: any;
    wx: any;
  }
}

// 初始化微信JSSDK
export const useWechatJSSDK = () => {
  const [isReady, setIsReady] = useState(false);

  useEffect(() => {
    // 动态加载微信JSSDK
    const loadWechatScript = () => {
      return new Promise<void>((resolve, reject) => {
        // 如果已经存在，不需要再加载
        if (window.WeixinJSBridge || document.querySelector('script[src*="jweixin"]')) {
          resolve();
          return;
        }

        const script = document.createElement('script');
        script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
        script.async = true;
        script.onload = () => {
          console.log('微信JS-SDK加载成功');
          resolve();
        };
        script.onerror = () => {
          console.log('主域名加载失败，尝试备用域名');
          // 主域名加载失败，尝试备用域名
          const backupScript = document.createElement('script');
          backupScript.src = 'https://res2.wx.qq.com/open/js/jweixin-1.6.0.js';
          backupScript.async = true;
          backupScript.onload = () => resolve();
          backupScript.onerror = () => reject(new Error('加载微信JS-SDK失败'));
          document.body.appendChild(backupScript);
        };
        document.body.appendChild(script);
      });
    };

    // 检查是否在微信浏览器中
    const isWechatBrowser = () => {
      const ua = navigator.userAgent.toLowerCase();
      return ua.indexOf('micromessenger') !== -1;
    };

    const initialize = async () => {
      try {
        await loadWechatScript();
        
        // 在微信浏览器中，我们可能还需要配置wx.config
        if (isWechatBrowser() && window.wx) {
          // 这部分通常需要后端接口提供签名等参数
          console.log('微信环境已准备就绪，可以使用JSSDK');
        }
        
        setIsReady(true);
      } catch (error) {
        console.error('初始化微信JS-SDK失败:', error);
      }
    };

    initialize();
  }, []);

  return { isReady };
};

// 调用微信支付
export const callWechatPay = (payParams: {
  appId: string;
  timeStamp: string;
  nonceStr: string;
  package: string;
  signType: string;
  paySign: string;
}) => {
  return new Promise((resolve, reject) => {
    // 检查是否在微信浏览器中
    const isWechatBrowser = () => {
      const ua = navigator.userAgent.toLowerCase();
      return ua.indexOf('micromessenger') !== -1;
    };
    
    // 如果不在微信浏览器中，提示用户
    if (!isWechatBrowser()) {
      return reject({ 
        success: false, 
        message: '请在微信浏览器中打开进行支付' 
      });
    }
    
    const onBridgeReady = () => {
      console.log('调用微信支付，参数：', {
        appId: payParams.appId,
        timeStamp: payParams.timeStamp,
        nonceStr: payParams.nonceStr,
        package: payParams.package,
        signType: payParams.signType,
        paySign: payParams.paySign
      });
      
      window.WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          "appId": payParams.appId,
          "timeStamp": payParams.timeStamp,
          "nonceStr": payParams.nonceStr,
          "package": payParams.package,
          "signType": payParams.signType,
          "paySign": payParams.paySign
        },
        function(res: any) {
          console.log('微信支付返回结果：', res);
          
          if (res.err_msg === "get_brand_wcpay_request:ok") {
            // 支付成功
            resolve({ success: true, message: '支付成功' });
          } else if (res.err_msg === "get_brand_wcpay_request:cancel") {
            // 用户取消
            resolve({ success: false, message: '支付已取消' });
          } else if (res.err_msg === "get_brand_wcpay_request:fail") {
            // 支付失败
            reject({ success: false, message: '支付失败，请重试' });
          } else {
            // 其他状态
            reject({ success: false, message: "支付结果异常: " + res.errMsg });
          }
        }
      );
    };

    // 检查WeixinJSBridge是否已加载
    if (typeof window.WeixinJSBridge === "undefined") {
      if (document.addEventListener) {
        document.addEventListener('WeixinJSBridgeReady', onBridgeReady as any, false);
      } else {
        // @ts-ignore - 兼容IE
        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
        // @ts-ignore - 兼容IE
        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
      }
    } else {
      onBridgeReady();
    }
  });
};

// JSAPI支付（需要wx.config配置）
export const callWechatJSAPIpay = (payParams: any) => {
  return new Promise((resolve, reject) => {
    // 确保wx对象已存在
    if (!window.wx) {
      return reject({ success: false, message: '微信JSSDK未加载' });
    }
    
    // 如果需要JSAPI支付，使用wx.chooseWXPay
    window.wx.chooseWXPay({
      timestamp: payParams.timeStamp, // 支付签名时间戳
      nonceStr: payParams.nonceStr, // 支付签名随机串
      package: payParams.package, // 统一支付接口返回的prepay_id参数值
      signType: payParams.signType, // 签名方式
      paySign: payParams.paySign, // 支付签名
      success: function (res: any) {
        resolve({ success: true, message: '支付成功' });
      },
      cancel: function (res: any) {
        resolve({ success: false, message: '支付已取消' });
      },
      fail: function (res: any) {
        reject({ success: false, message: '支付失败: ' + JSON.stringify(res) });
      }
    });
  });
};
